package puziran.sofa.util;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * @author wusong
 * @version : 1.0
 * @copyright 
 * @Create Time : 2012-10-26 
 * @Description : 服务定向工具类
 * @History：Editor　　　version　　　Time　　　　　Operation　　　　　　　Description*
 *
 */
public class JsonGenerateUtil{
	public static Logger log = LoggerFactory.getLogger(JsonGenerateUtil.class); 

	public static String object2json(Object obj) {
		StringBuilder json = new StringBuilder();
		if (obj == null) {
			json.append("\"\"");
		} else if (obj instanceof String || obj instanceof Integer
				|| obj instanceof Float || obj instanceof Boolean
				|| obj instanceof Short || obj instanceof Double
				|| obj instanceof Long || obj instanceof BigDecimal
				|| obj instanceof BigInteger || obj instanceof Byte) {
			json.append("\"").append(string2json(obj.toString())).append("\"");
		} else if (obj instanceof Object[]) {
			json.append(array2json((Object[]) obj));
		} else if (obj instanceof List) {
			json.append(list2json((List<?>) obj));
		} else if (obj instanceof Map) {
			json.append(map2json((Map<?, ?>) obj));
		} else if (obj instanceof Set) {
			json.append(set2json((Set<?>) obj));
		} else {
			json.append(bean2json(obj));
		}
		return json.toString();
	}

	/**
	 * @param bean:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-08-03
	 * @description : bean转换为json
	 */
	public static String bean2json(Object bean) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		PropertyDescriptor[] props = null;
		try {
			props = Introspector.getBeanInfo(bean.getClass(), Object.class)
					.getPropertyDescriptors();
		} catch (IntrospectionException e) {
		}
		if (props != null) {
			for (int i = 0; i < props.length; i++) {
				try {
					String name = object2json(props[i].getName());
					String value = object2json(props[i].getReadMethod().invoke(
							bean));
					json.append(name);
					json.append(":");
					json.append(value);
					json.append(",");
				} catch (Exception e) {
				}
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * @param list:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-08-03
	 * @description : list转换为json
	 */
	public static String list2json(List<?> list) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	/**
	 * @param array:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-08-03
	 * @description : array转换为json
	 */
	public static String array2json(Object[] array) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (array != null && array.length > 0) {
			for (Object obj : array) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	/**
	 * @param map:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-08-03
	 * @description : map转换为json
	 */
	public static String map2json(Map<?, ?> map) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (map != null && map.size() > 0) {
			for (Object key : map.keySet()) {
				json.append(object2json(key));
				json.append(":");
				json.append(object2json(map.get(key)));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * @param set:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-08-03
	 * @description : set转换为json
	 */
	public static String set2json(Set<?> set) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (set != null && set.size() > 0) {
			for (Object obj : set) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String string2json(String s) {
		if (s == null)
			return "";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}
		return sb.toString();
	}
	
	/**
	 * @param obj:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-11-11
	 * @description : list转换为json 返回所有，不用于分页    格式：[{"id":"1","name":"ws"},{"id":"2","name":"sw"}]
	 */
	public static String getListJson(List list){
		String cJson = JsonGenerateUtil.list2json(list);
		return cJson;
	}
	
	/**
	 * @param obj:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-11-11
	 * @description : list转换为json 用于分页 适合kendo UT grid 格式：{"Count":"100","Data":"[{"id":"1","name":"ws"},{"id":"2","name":"sw"}]"}
	 */
	public static String getPageListJson(List list,String count){
		String cJson = JsonGenerateUtil.list2json(list);
		String r = "{\"Count\":"+count +",\"Data\":"+cJson+"}";
//		log.debug("sofa:"+r);
		return r;
	}
	
	/**
	 * @param msg:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-11-11
	 * @description : 后台返回的msg=ok|sorry|其他自定义值，转换为json，格式：{"msg":"msgstr"}
	 */
	public static String getMsgJson(String msg){
		String cJson = JsonGenerateUtil.string2json(msg);
		return "{\"msg\":\""+cJson+"\"}";
	}
	
	/**
	 * @param msg:ok|sorry|其他自定义值
	 * @param id:返回新增记录的自增id值
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-11-11
	 * @description : 后台返回的msg,id转换为json 格式：{"msg":"msgstr","id":"id"}
	 */
	public static String getMsgIdJson(String msg,String id){
		String cJson = JsonGenerateUtil.string2json(msg);
		return "{\"msg\":\""+cJson+"\",\"id\":\""+id+"\"}";
	}
	
	
	/**
	 * @param msg:ok|sorry|其他自定义值
	 * @param id:返回新增记录的自增id值
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2012-11-11
	 * @description : 自定义json格式
	 */
	public static String getSelfDefinedJson(String msg){
		String cJson = JsonGenerateUtil.string2json(msg);
		return cJson;
	}
	

	public void f_additem(List list, String vcItem, String vcValue) {
		//返回json可处理的list
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("item", vcItem.toLowerCase()); //返回的键名必须是小写
		if (null==vcValue) vcValue="";
		map.put("value", vcValue);	
		list.add(map);
	}
	
	
	public void f_additem(List list, List sqlList) {
		//把sql返回的list对象处理成返回json可处理的list
		if (sqlList==null || sqlList.size()<1) return; //无数据 	
		Map mapList= (Map)sqlList.get(0);
		
		Set<Entry<String, String>> set = mapList.entrySet();
		Iterator<Entry<String,String>> ite = set.iterator();
		while(ite.hasNext()){
			Map<String, Object> map = new HashMap<String, Object>();
			Entry<String,String> entry = ite.next();
			map.put("item", entry.getKey().toLowerCase()); //返回的键名必须是小写
			map.put("value", entry.getValue());	
			list.add(map);
		} 			
		
	}
	
	
	/**
	 * @param obj:
	 * @return :json串
	 * @author : wusong
	 * @version : 1.0
	 * @create time : 2013-11-8
	 * @description :将数据转为嵌套json 格式：{"check":"100","cmd":"AuditUser","timestamp":"2013-11-08 11:11:111","status":"200","result":"[{"id":"1","name":"ws"},{"id":"2","name":"sw"}]"}
	 */
	public static String getNestJson(String check,String cmd,String timestamp,String status,Object result){
		String cJson = JsonGenerateUtil.object2json(result);
		String r = "{\"check\":\""+check +"\",\"cmd\":\""+cmd +"\",\"timestamp\":\""+timestamp +"\",\"status\":\""+status +"\",\"result\":"+cJson+"}";
//		log.debug("sofa:"+r);
		return r;
	}
	
	
}
